<template>
	<view class="add">
		<headertop :title="quert.id?'编辑':'添加'" str1="oridei" :back1="back1"></headertop>
		<view class="addback">

		</view>
		<view class="" :style="{'margin-top':statusBarHeight+'px','width':'100%','height':barHeight+'px'}">
		</view>
		<view class="centerboxform">
			<view class="centerbox">
				<view class="linebox">
					<view style="display: flex;align-items: center;">
						<span style="color: #F53F3F;">*</span>
						<span>制剂：</span>
					</view>
					<view class="rightbpxx" @click="open('制剂')">
						<input type="text" v-model="quert['name']" placeholder="请选择" :disabled="true"
							v-if="!quert['biological_id']" />
						<span v-else>{{text(arr,quert['biological_id'])}}</span>
						<image :src="_static('/images/Frame@2x(6).png')" class="arrowright" mode="">
						</image>
					</view>
				</view>
				<view class="linebox">
					<view style="display: flex;align-items: center;">
						<span style="color: #F53F3F;">*</span>
						<span>体重：</span>
					</view>
					<view style="display: flex;align-items: center;font-size: 28rpx;">
						<input type="digit" v-model="quert['weight']" placeholder="请输入体重" />
						<span style="margin-left: 10rpx;">kg</span>
					</view>
				</view>
				<view class="linebox">
					<view style="display: flex;align-items: center;">
						<span style="color: #F53F3F;">*</span>
						<span>剂量：</span>
					</view>
					<input type="digit" v-model="quert['dose']" placeholder="请输入剂量" />
				</view>
				<view class="linebox" style="border: none;">
					<view style="display: flex;align-items: center;">
						<span style="color: #F53F3F;">*</span>
						<span>注射日期：</span>
					</view>
					<view style="display: flex;align-items: center;font-size: 28rpx;">
						<input type="text" v-model="quert['injection_time']" @click="open('注射日期')" :disabled="true"
							placeholder="请选择注射日期" />
						<image :src="_static('/images/Frjt.png')" class="rightarrow" mode="">
						</image>
					</view>

				</view>
			</view>
		</view>
		<view class="fixed">
			<view class="savebtn" @click="save">
				保存
			</view>
		</view>
		<up-popup :show="show" mode="bottom">
			<view class="xuanxiang">
				<view class="tt" style="margin-left: 30rpx;color: #888;" @click="show=false">
					取消
				</view>
				<view class="tt" style="font-weight: 600;">
					{{titlepopu}}
				</view>
				<view class="tt" style="margin-right: 30rpx;color: #0077BE;" @click="queding">
					确认
				</view>
			</view>
			<picker-view immediate-change="true" :indicator-style="indicatorStyle" :value="zhuanind(arr,quert['name'])"
				@change="bindChange" class="picker-view" v-if="titlepopu!='请选择注射日期'">
				<picker-view-column>
					<view class="item" v-for="(item,index) in arr" :key="index">{{item.name}}</view>
				</picker-view-column>
			</picker-view>
			<picker-view :indicator-style="indicatorStyle" immediate-change="true" :value="valuedate"
				@change="bindChange" class="picker-view" v-if="titlepopu=='请选择注射日期'">
				<picker-view-column>
					<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in 24" :key="index">{{item}}时</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item">0分</view>
					<view class="item" v-for="(item,index) in 59" :key="index">{{item}}分</view>
				</picker-view-column>
			</picker-view>
		</up-popup>
	</view>
</template>
<script setup>
	import headertop from '@/components/header.vue'
	import {
		_static
	} from '@/ulm/utils/url.js'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onPageScroll,
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	const statusBarHeight = ref('')
	import ulm, {
		$api
	} from '@/ulm';
	const texts = ref('')
	const indicatorStyle = ref(`height: 50px;`)
	const barHeight = ref('')
	const arr = ref([])
	const val = ref([0])
	const back1 = ref('')
	const show = ref(false)
	const active = ref(2)
	const biological_id = ref('')
	const quert = reactive({
		biological_id: '',
		weight: '',
		injection_time: '',
		dose: '',
		id: undefined
	})
	const injection_time = ref('')
	const date = new Date()
	const years = []
	const year = date.getFullYear()
	const months = []
	const month = date.getMonth() + 1
	const days = []
	const day = date.getDate()
	const hours = date.getHours();
	// 获取当前分钟
	const minutes = date.getMinutes();
	const valuedate = ref([9999, month - 1, day - 1, hours - 1, minutes])
	for (let i = 1900; i <= date.getFullYear(); i++) {
		years.push(i)
	}
	for (let i = 1; i <= 12; i++) {
		months.push(i)
	}
	for (let i = 1; i <= 31; i++) {
		days.push(i)
	}
	const titlepopu = ref('')
	onLoad((opt) => {
		init()
		quert.id = opt.id
		if (opt.id) {
			var obj = uni.getStorageSync('itemobj')
			quert['biological_id'] = obj.biological_id
			quert['weight'] = obj.weight
			quert['dose'] = obj.dose
			quert['injection_time'] = timestampToHoursMinutes(obj.injection_time * 1000)
		}
	})

	function zhuanind(arr, ite) {
		var ind = arr.findIndex(item => item['id'] == ite)
		if (ind == -1) {
			ind = 0
		}
		return [ind]
	}

	function padStart(n) {
		return n.toString().padStart(2, 0)
	}


	function timestampToHoursMinutes(timestamp) {
		const date = new Date(timestamp)
		const year = date.getFullYear()
		const month = padStart(date.getMonth() + 1)
		const day = padStart(date.getDate())
		const house = padStart(date.getHours())
		const minuse = padStart(date.getMinutes())
		return ` ${year}-${month}-${day}  ${house}:${minuse}`;
	}


	function open(str) {
		titlepopu.value = '请选择' + str
		show.value = true
	}
	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;
	})
	onPageScroll((e) => {
		if (e.scrollTop > 100) {
			back1.value = '#81D6FF'
		} else {
			back1.value = ''
		}
	})
	async function init() {
		const res = await $api.biologicalList()
		if (res.code == 1) {
			arr.value = res.data
		}
	}

	function bindChange(e) {
		const val = e.detail.value
		if (titlepopu.value != '请选择注射日期') {
			biological_id.value = arr.value[val[0]]['id']
		} else {
			injection_time.value =
				`${years[val[0]]}-${months[val[1]]<10?'0'+months[val[1]]:months[val[1]]}-${days[val[2]]<10?'0'+days[val[2]]:days[val[2]]} ${val[3]+1>=10?val[3]+1:'0'+(val[3]+1)}:${val[4]>=10?val[4]:'0'+val[4]}`
		}
	}

	function queding() {
		if (titlepopu.value != '请选择注射日期') {
			if (!biological_id.value) {
				quert.biological_id = arr.value[0]['id']
			} else {
				quert.biological_id = biological_id.value
			}
		} else {
			if (!injection_time.value) {
				quert.injection_time =
					`${date.getFullYear()}-${months[month-1]<10?'0'+months[month-1]:months[month-1]}-${day<10?'0'+day:day} ${hours>=10?hours:'0'+hours}:${minutes>=10?minutes:'0'+minutes}`
			} else {

				quert.injection_time = injection_time.value
				if (convertToTimestamp(quert.injection_time) > Date.now()) {
					quert.injection_time = ''
					uni.showToast({
						title: '请选择正确注射时间',
						icon: 'none'
					})
					return
				}
			}
		}
		show.value = false
	}

	function convertToTimestamp(dateStr) {
		return new Date(dateStr).getTime();
	}

	function text(arr, id) {
		var ind = arr.findIndex(item => item.id == id)
		if (ind == -1) {
			return ''
		} else {
			return arr[ind]['name']
		}
	}
	async function save() {
		for (var i in quert) {
			if (!quert[i]) {
				if (i != 'id') {
					uni.showToast({
						title: '请补全后提交',
						icon: 'none'
					})
					return
				}
			}
		}
		if (quert['weight'] * 1 > 200) {
			uni.showToast({
				title: '体重不能超过200kg',
				icon: 'none'
			})
			return
		}
		if (convertToTimestamp(quert['injection_time']) > Date.now()) {
			quert['injection_time'] = ''
			uni.showToast({
				title: '请选择正确注射日期',
				icon: 'none'
			})
			return
		}
		if (quert.id) {
			const res1 = await $api.editbiological(quert)
			if (res1.code == 1) {
				uni.navigateBack()
				setTimeout(() => {
					uni.showToast({
						title: '编辑成功'
					})
				}, 500)
			} else {
				uni.showToast({
					title: res1.msg,
					icon: 'none'
				})
			}
			return
		}
		const res = await $api.addsw(quert)
		if (res.code == 1) {
			uni.navigateBack()
			setTimeout(() => {
				uni.showToast({
					title: '添加成功'
				})
			}, 500)
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	}
</script>
<style lang="scss">
	.rightarrow {
		width: 24rpx;
		height: 24rpx;
	}

	::v-deep .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	.picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.xuanxiang {
		width: 100%;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		overflow: hidden;
		justify-content: space-between;
		margin-bottom: 30rpx;

		.tt {
			font-size: 32rpx;
		}
	}

	page {
		background: #F7F8FA;
	}

	.add {
		width: 100%;
		overflow: hidden;
		position: relative;

		.fixed {
			width: 100%;
			background: #FFFFFF;
			overflow: hidden;
			position: fixed;
			bottom: 0%;

			.savebtn {
				width: 686rpx;
				height: 82rpx;
				background: #2AB4F5;
				border-radius: 12rpx 12rpx 12rpx 12rpx;
				text-align: center;
				line-height: 82rpx;
				font-size: 32rpx;
				color: #FFFFFF;
				margin: auto;
				margin-top: 32rpx;
				margin-bottom: 80rpx;
			}
		}

		.addback {
			height: 450rpx;
			background: linear-gradient(180deg, #CAEEFF 71%, rgba(240, 250, 255, 0) 100%);
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			width: 100%;
			position: absolute;
			z-index: -1;
		}

		.centerboxform {
			width: 686rpx;
			height: 368rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			margin: auto;
			margin-top: 32rpx;

			.centerbox {
				width: 630rpx;
				margin: auto;

				.linebox {
					width: 100%;
					height: 88rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 2rpx solid #F2F3F5;
					font-size: 28rpx;

					.rightbpxx {
						display: flex;
						align-items: center;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #86909C;

						input {
							text-align: right;
						}

						.arrowright {
							width: 24rpx;
							height: 24rpx;
							margin-left: 12rpx;
						}
					}

					input {
						text-align: right;
						font-size: 28rpx;
					}

				}
			}
		}
	}
</style>